//
//  HMHomeTableViewController.swift
//  ZQWeibo
//
//  Created by summer的Dad on 16/11/12.
//  Copyright © 2016年 summer的Dad. All rights reserved.
 

import UIKit
import SVProgressHUD


private let statusCellID = "statusID"
private let retweeteCellID = "retweetedStatus"
let orginalCell = UINib(nibName: "ZQstatusTableViewCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! ZQstatusTableViewCell
let reweetedCell = UINib(nibName: "ZQRetweetedStatusCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! ZQstatusTableViewCell

class ZQHomeTableViewController: ZQBaseTableViewController {
   lazy var needLoadArray: [IndexPath] = [IndexPath]()
    
    lazy var homeViewModel : ZQHomeViewModel = ZQHomeViewModel()
    lazy var refieshControl : ZQRefieshControl = ZQRefieshControl()
     var count = 0
    //定义视图的大小
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        
    }

    
     override func viewDidLoad() {
        super.viewDidLoad()

        if !userlogin {
            
            visitroLogin.vistitorInfo(title: "快来看看,这里有很多惊喜等着您")
   
            return
        }
        
        
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem( imageName: "navigationbar_pop", target: self, action: #selector(pust))
        

        //主页面
        setupTabViwController()
        //加载数据
        loadData()
        
    }
    
  
    func loadData () {
        
        
        //加载数据
        homeViewModel.loadData(isPullup: indcatorView.isAnimating){ (isSuccess, count) in
        
            if !isSuccess {
                
                return
            }
            
            if !self.indcatorView.isAnimating{
                //开始动画
                self.stardAnimation(count: count)
        
            }
            
           
            //停止转动
           self.indcatorView.stopAnimating()
            //上面的停止转动
//            self.refreshControl?.endRefreshing()
        
            self.refieshControl.endReshing()
            //开始转动
            self.tableView.reloadData()
            
        }
            
    }
    //开始动画
    private func stardAnimation(count : Int){
        
        if tipLable.isHidden == false {
            
            return
        }
        
     
        let tiplable = count == 0 ? "没有微博" : "有 \(count)条微博"
        
        tipLable.isHidden = false
        //控件赋值
        tipLable.text = tiplable
        //记录一下原来的位置
        let y = self.tipLable.frame.origin.y
        //动画
        UIView.animate(withDuration: 1, animations: {
            self.tipLable.frame.origin.y = navBarHeight
        },completion: { (_) in
        UIView.animate(withDuration: 1, animations: { 
            self.tipLable.frame.origin.y = y
        }, completion: { (_) in
            
           self.tipLable.isHidden = true
        })
     
        })

    }
    
     //懒加载
     lazy var indcatorView : UIActivityIndicatorView = {
        
        //创建一个小菊花
         let indcator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        return indcator
        
    }()
    
    
    //tableVIew
   private func setupTabViwController (){
    
    
    
    
        // 注册tableView
        let nib = UINib(nibName:"ZQstatusTableViewCell" ,bundle: nil)
        
        tableView.register(nib, forCellReuseIdentifier: statusCellID)
    
        let nib1 = UINib(nibName:"ZQRetweetedStatusCell" ,bundle: nil)
    
        tableView.register(nib1, forCellReuseIdentifier: retweeteCellID)
    

    
        //自定义fieshControl
//        let refish  = ZQRefieshControl()
    
        refieshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
    
        self.view.addSubview(refieshControl)
    
//        self.view.addSubview(refish)
        //设置自适应行高
        tableView.separatorStyle = .none
        //尾部小菊花
        tableView.tableFooterView = indcatorView
        //加载lable视图
         tipLable.frame = CGRect(x: 0, y: 0, width:ScreenWidth, height: 35)
        //显示weihzi
         tipLable.frame.origin.y = navBarHeight - 35
    
        //添加到navigantionbar上
        self.navigationController?.view.insertSubview(tipLable, belowSubview: self.navigationController!.navigationBar)
    
    
    
    
    }
    //懒加载一个提示lable
    private lazy var tipLable : UILabel = {
        
        let l = UILabel(title: "", fontSize: 16, textColor: UIColor.white)
        
        l.backgroundColor = UIColor.orange
        l.textAlignment = .center
        
        l.isHidden = true
        
        return l
        
    }()
    
//POST到子页面
     @objc private  func pust () {
        
        let demo = ZQDemoController()
//        let parameters = ["access_token" : ZQUserAccountViewModel.shared.access_token  ]
        self.navigationController?.pushViewController(demo, animated: true)
        
        
    }

}
//分类

extension ZQHomeTableViewController {
    
    
    //返回行
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return homeViewModel.statusViewModel.count
    }
    
    //返回数据cell
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //拿到数据模型
        let viewModel = self.homeViewModel.statusViewModel[indexPath.row]
        //返回cell
        let cellID = getCellId(viewmodel: viewModel)
        //出队列
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
            as! ZQstatusTableViewCell
        
        
        
        //如果需要加载的数组的数量大于0 并且 正要加载的indexPath不在按需加载的数组中 就不渲染cell
        if needLoadArray.count > 0 {
            let result = needLoadArray.contains(where: { (index) -> Bool in
                return index.row == indexPath.row && index.section == indexPath.section
            })
            if !result {
               
                return cell
            }
        }
        cell.viewmodel = viewModel
        
        return cell
    }
    
    //如果在这里完成自定刷新控件UI的更新, 这就是强耦合
    override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        guard let ip = tableView.indexPathForRow(at: CGPoint(x: 0, y: targetContentOffset.pointee.y)) else {
            return
        }
        guard let cip = tableView.indexPathsForVisibleRows?.first else {
            return
        }
        
        let skipCount = 12;
        
        if labs(cip.row - ip.row) > skipCount {
            guard let temp = tableView.indexPathsForRows(in: CGRect(x: 0, y: targetContentOffset.pointee.y, width: self.view.frame.width, height: self.view.frame.height)) else {
                
                return
            }
            var arr = temp
            print(velocity.y)
            //向下滑动
            if velocity.y < 0 {
                
                let indexPath = temp.last!
                if (indexPath.row + 3 < self.homeViewModel.statusViewModel.count) {
                    arr.append(IndexPath(row: indexPath.row + 1, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row + 3, section: 0))
                }
            }else{
                //向上滑动
                let indexPath = temp.first!
                if (indexPath.row > 3) {
                    arr.append(IndexPath(row: indexPath.row - 3, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 2, section: 0))
                    arr.append(IndexPath(row: indexPath.row - 1, section: 0))
                }
            }
            needLoadArray.append(contentsOf: arr)
        }
    }
    //自动计算行高
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
             let viewModel = self.homeViewModel.statusViewModel[indexPath.row]
        
//            let name = nibName(Viewmodel: viewModel)
        
//        let cell = UINib(nibName: name, bundle: nil).instantiate(withOwner: nil, options: nil).last as! ZQstatusTableViewCell
        
            count = count + 1
        
//            cell.viewmodel = viewModel
        
//            cell.layoutIfNeeded()
        
//        return cell.toolBar.frame.maxY
        return viewModel.rowHeight
    }
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("开始")
        needLoadArray.removeAll()
    }
    
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("结束")
        needLoadArray.removeAll()
    }
    
    //判断下面倒数第二个开始旋转小菊花
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indcatorView.isAnimating == false && indexPath.row == homeViewModel.statusViewModel.count - 2{
            
            indcatorView.startAnimating()
            
            loadData()
        }
      
       
    }
    
 
  //返回注册cellID
//    func nibName(Viewmodel : ZQstatusViewModel) -> String {
//        
//        return Viewmodel.status?.retweeted_status == nil ? "ZQstatusTableViewCell" : "ZQRetweetedStatusCell"}
//    

    private func getCellId(viewmodel: ZQstatusViewModel) -> String {
        return viewmodel.status?.retweeted_status == nil ? statusCellID : retweeteCellID
    }

    
    
    
    
    
}


